package com.abcgz.grade;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.abcgz.grade.model.RestResult;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	//添加全局异常处理流程，根据需要设置需要处理的异常，本文以MethodArgumentNotValidException为例
	@ExceptionHandler(value=MethodArgumentNotValidException.class)
	public Object MethodArgumentNotValidHandler(HttpServletRequest request,
			MethodArgumentNotValidException exception) throws Exception
	{
		//按需重新封装需要返回的错误信息
		List<String> invalidArguments = new ArrayList<>();
		//解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
		for (FieldError error : exception.getBindingResult().getFieldErrors()) {
			invalidArguments.add(error.getDefaultMessage());
		}
		
		RestResult resultMsg = new RestResult(false, String.join("", invalidArguments));
		return resultMsg;
	}
	
	@ExceptionHandler(value=BindException.class)
	public Object BindExceptionHandler(HttpServletRequest request,
			BindException exception) throws Exception
	{
		//按需重新封装需要返回的错误信息
		List<String> invalidArguments = new ArrayList<>();
		//解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
		for (FieldError error : exception.getBindingResult().getFieldErrors()) {
			invalidArguments.add(error.getDefaultMessage());
		}
		
		RestResult resultMsg = new RestResult(false, String.join("，", invalidArguments));
		return resultMsg;
	}
	
	@ExceptionHandler(value=GradeException.class)
	public Object FaceLoanExceptionHandler(HttpServletRequest request,
			GradeException exception) throws Exception
	{
		RestResult resultMsg = new RestResult(false, exception.getMessage());
		return resultMsg;
	}
}